import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:squat_easy/generated/assets.dart';
import 'package:squat_easy/se_constant.dart';
import 'package:squat_easy/se_main/se_mine/se_edit_info/se_edit_info_logic.dart';
import 'package:squat_easy/se_main/se_mine/se_mine_base_page.dart';
import 'package:squat_easy/se_service/se_user_service.dart';
import 'package:squat_easy/se_standard/se_app_colors.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

class SeEditInfoPage extends GetView<SeEditInfoLogic> {
  const SeEditInfoPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SeEditInfoLogic>(
      init: SeEditInfoLogic(),
      assignId: true,
      builder: (logic) {
        return SeMineBasePage(
          actions: [
            ValueListenableBuilder(
              valueListenable: logic.enableSubmit,
              builder: (BuildContext context, bool value, Widget? child) {
                return ButtonWidget.icon(
                  ImageWidget.asset(
                    value ? Assets.pngMineRadioSelect : Assets.pngMineRadioNormal,
                    width: 40,
                    height: 40,
                  ),
                  onTap: logic.submit,
                  hasInkWell: false,
                );
              },
            )
          ],
          child: ValueListenableBuilder(
            valueListenable: SeUserService.instance.notifierOfMineInfo,
            builder: (BuildContext context, value, Widget? child) {
              return Column(
                children: [
                  _buildAvatar().paddingTop(40.w),
                  _buildItem('Nick Name', right: _buildNameInput()).paddingTop(34.w),
                  _buildItem('Date of Birth', right: _buildChooseBirth()).paddingTop(42.w),
                  _buildItem('Country', right: _buildChooseCountry()).paddingTop(42.w),
                ],
              );
            },
          ),
        );
      },
    );
  }

  Widget _buildNameInput() {
    return TextField(
      controller: controller.textEditingController,
      style: const TextStyle(fontSize: 19, color: Colors.white),
      textAlign: TextAlign.right,
      decoration: InputDecoration(
        hintText: '',
        hintStyle: const TextStyle(fontSize: 19, color: SeAppColors.text3),
        contentPadding: EdgeInsets.symmetric(vertical: 14.w),
        border: InputBorder.none,
        isCollapsed: true,
        enabledBorder: const UnderlineInputBorder(borderSide: BorderSide(color: Colors.transparent)),
        focusedBorder: const UnderlineInputBorder(borderSide: BorderSide(color: Colors.transparent)),
      ),
      inputFormatters: [LengthLimitingTextInputFormatter(SeInputLimit.nameLimit)],
    );
  }

  Widget _buildChooseBirth() {
    return ButtonWidget.text(
      controller.birth.value,
      textColor: Colors.white,
      fontSize: 19,
      alignment: Alignment.centerRight,
      height: 54.w,
      hasInkWell: false,
      onTap: () {
        ActionBottomSheet.showDatePicker(
          onConfirm: (DateTime? dateTime, String year, String month, String day) {
            if (dateTime == null) return;
            int age = DateTime.now().year - dateTime.year;
            if (age < 18) {
              Loading.toast('You must be at least 18 years old');
              return;
            }
            controller.birth.value = '$year-${toDouble(month)}-${toDouble(day)}';
            controller.update();
          },
        );
      },
    );
  }

  String toDouble(String value) {
    if (value.length == 1) {
      return '0$value';
    }
    return value;
  }

  Widget _buildChooseCountry() {
    return ButtonWidget.text(
      controller.country.value,
      textColor: Colors.white,
      fontSize: 19,
      alignment: Alignment.centerRight,
      height: 54.w,
      hasInkWell: false,
      onTap: () {
        if (controller.countryList.isEmpty) return;
        ActionBottomSheet.showDataPicker(
          data: controller.countryList,
          onConfirm: (String value) {
            controller.country.value = value;
            controller.update();
          },
        );
      },
    );
  }

  Widget _buildAvatar() {
    String avatar = SeUserService.instance.notifierOfMineInfo.value.avatarThumbUrl ?? '';
    bool editAvatar = CommonStorage().getBool(SeUserService.instance.editAvatarKey, defaultValue: false);
    return ButtonWidget(
      onTap: controller.changeAvatar,
      hasInkWell: false,
      child: Stack(
        children: [
          !controller.filePath.value.startsWith('http')
              ? ImageWidget.file(
                  controller.filePath.value,
                  width: 120.w,
                  height: 120.w,
                  radius: 120.w,
                  fit: BoxFit.cover,
                )
              : ImageWidget.url(
                  editAvatar ? avatar : '',
                  width: 120.w,
                  height: 120.w,
                  radius: 120.w,
                  fit: BoxFit.cover,
                  placeholder: ImageWidget.asset(Assets.pngDefaultAvatar, width: 120.w, height: 120.w, radius: 120.w),
                ),
          IconWidget.image(Assets.pngAvatarCamera, size: 26.w).positioned(top: 0, right: 5.w),
        ],
      ),
    );
  }

  Widget _buildItem(String title, {Widget? right}) {
    return ButtonWidget(
      height: 54.w,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      backgroundColor: Colors.black,
      borderRadius: 12.w,
      child: Row(
        children: [
          TextWidget.oneLine(text: title, fontSize: 19, color: Colors.white),
          if (right != null) right.expanded(),
        ],
      ),
    ).paddingHorizontal(20.w);
  }
}
